
local voucherId = ARGV[1]

local userId = ARGV[2]

local orderId = ARGV[3]

local stockKet = 'seckill:stock:' .. voucherId

local orderKey = 'seckill:order:' .. voucherId

--judge if the stock is bingger than 0
if (tonumber(redis.call('get', stockKet)) <= 0) then
    -- 库存不足
    return 1
end

--judge if the user has bought the voucher
if (redis.call('sismember', orderKey, userId) == 1) then
    -- 用户已经购买过，现在是重复下单
    return 2
end

redis.call('incrby', stockKet, -1)

redis.call('sadd', orderKey, userId)

-- 发送消息存储到消息队列中

redis.call('xadd', 'stream.orders', '*', 'userId', userId, 'voucherId', voucherId, 'id', orderId)

return 0